package com.nondo.dean.platform.controller.api.app;

import com.nondo.dean.auth.client.DeanAuthClient;
import com.nondo.dean.auth.client.annotation.LazyAutowired;
import com.nondo.dean.auth.common.TokenPrincipal;
import com.nondo.dean.auth.common.TokenPrincipalProvider;
import com.nondo.dean.auth.common.annotation.HasUser;
import com.nondo.dean.auth.common.bean.SendType;
import com.nondo.dean.auth.common.bean.UserItem;
import com.nondo.dean.common.annotation.ApiVersion;
import com.nondo.dean.common.thirdpart.ueditor.define.State;
import com.nondo.dean.common.thirdpart.ueditor.upload.Base64Uploader;
import com.nondo.dean.common.tool.*;
import com.nondo.dean.common.web.View;
import com.nondo.dean.platform.cache.RegisterStatusCache;
import com.nondo.dean.platform.domain.User;
import com.nondo.dean.platform.model.SendBean;
import com.nondo.dean.platform.model.UserBean;
import com.nondo.dean.platform.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.util.*;

import static com.nondo.dean.common.tool.AliyunOssTool.OSS_TOOL_KEY;

/**
 * project：dean-cloud
 *
 * @author linfeng @ nondo
 * @date 2018/5/9
 */
@RestController("apiAppUser")
@RequestMapping("/{v}/app/user")
public class UserController {

    @Autowired
    private UserService userService;

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @LazyAutowired
    private DeanAuthClient deanAuthClient;
    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    private TokenPrincipalProvider tokenPrincipalProvider;
    @Autowired
    private AliyunOssTool ossTool;
    @Autowired
    private RegisterStatusCache registerStatusCache;

    @HasUser
    @ApiVersion(1)
    @RequestMapping("/info")
    public View<Map<String, Object>> info() {

        TokenPrincipal tokenPrincipal = tokenPrincipalProvider.getTokenPrincipal();
        String username = tokenPrincipal.getUsername();
        String mobile = tokenPrincipal.getMobile();

        View<Map<String, Object>> view = new View<>(20000, "获取数据成功");

        User user = userService.selectUserByName(username);
        if (user == null) {
            user = new User();
        }

        if (StringUtils.isNotBlank(mobile) && !mobile.equals(user.getMobile())) {
            user.setMobile(mobile);
            userService.updateUser(user);
        }

        List<String> includeFields = new ArrayList<>();
        includeFields.add("id");
        includeFields.add("userName");
        includeFields.add("nickName");
        includeFields.add("mobile");
        includeFields.add("avatar");
        includeFields.add("childAccount");
        List<String> sensitiveKey = new ArrayList<>();
        Map<String, Object> userMap = ObjectUtils.objectToMap(user, includeFields, sensitiveKey);
        view.setData(userMap);
        return view;
    }

    /**
     * 更新用户
     *
     * @param request
     * @param response
     * @param user     用户信息 {@link User}
     * @return
     */
    @ApiVersion(1)
    @RequestMapping("/info/update")
    public View<User> update(HttpServletRequest request,
                             HttpServletResponse response,
                             @Validated @RequestBody User user, BindingResult result) {
        View<User> view = new View<User>(20000, "更新成功");


        if (result.hasErrors()) {
            view.setCode(40000);
            view.setMessage(ValidateUtil.first(result.getAllErrors()));
        } else {

            String username = tokenPrincipalProvider.getTokenPrincipal().getUsername();
            User userDb = userService.selectUserByName(username);
            BeanUtils.copy(user, userDb);
            this.userService.updateUser(userDb);
        }

        return view;
    }


    /**
     * 更新用户
     *
     * @param request
     * @param response
     * @param userBean 用户信息 {@link UserBean}
     * @return
     */
    @HasUser
    @ApiVersion(1)
    @RequestMapping("/avatar/update")
    public View<User> avatarUpdate(HttpServletRequest request,
                                   HttpServletResponse response,
                                   @Validated @RequestBody UserBean userBean, BindingResult result) {

        if (result.hasErrors()) {

            return View.ofError(40000, ValidateUtil.first(result.getAllErrors()));
        } else {

            String username = tokenPrincipalProvider.getTokenPrincipal().getUsername();
            User userDb = userService.selectUserByName(username);
            if (userDb == null) {
                return View.ofError("更新用户头像失败");
            }

            String fileName = UUID.randomUUID().toString();
            LocalDate localDate = LocalDate.now();
            Map<String, Object> conf = new HashMap<>();
            conf.put("maxSize", Long.MAX_VALUE);
            conf.put("savePath", localDate.getYear() + "/" + userDb.getUserNo() + "/" + fileName);
            conf.put("filename", fileName);
            conf.put("rootPath", "avatar/");
            conf.put("OSS_FILE_CACHE_KEY", "oss_avatar_key");
            conf.put(OSS_TOOL_KEY, ossTool);
            State state = Base64Uploader.save(userBean.getAvatarBase64(), conf);

            if (state.isSuccess()) {
                userDb.setAvatar(state.getStoreUrl());
                this.userService.updateUser(userDb);
                return View.ofOk("更新用户头像成功");
            } else {
                return View.ofError("更新用户头像失败");
            }

        }

    }

    /**
     * 发送验证码
     *
     * @return
     */
    @ApiVersion(1)
    @RequestMapping("/sms/send")
    public View<User> smsSend(@Validated @RequestBody(required = false) SendBean user, BindingResult result) {

        if (result.hasErrors()) {
            return View.ofError(40000, ValidateUtil.first(result.getAllErrors()));
        } else {

            TokenPrincipal tokenPrincipal = tokenPrincipalProvider.getTokenPrincipal();
            if (tokenPrincipal == null) {
                return View.ofError("用户没有登录");
            }
            String username = tokenPrincipal.getUsername();

            User userDb = userService.selectUserByName(username);
            if (userDb == null || StringUtils.isEmpty(userDb.getMobile())) {
                return View.ofError("当前用户没有绑定手机号，请绑定");
            }
            String mobile = userDb.getMobile();

            Map<String, String> params = new HashMap<>();
            params.put("username", mobile);
            params.put("send_type", user.getSendType() == null ? SendType.modify.name() : user.getSendType());
            View<String> clientView = deanAuthClient.registerVerificationCodeEndpoint(params);
            if (clientView.getCode() == View.STATE_OK) {
                return View.ofOk("发送成功");
            } else {
                return View.ofError(clientView.getMessage());
            }
        }
    }

    /**
     * 更新用户
     *
     * @param request
     * @param response
     * @param user     用户信息 {@link User}
     * @return
     */
    @ApiVersion(1)
    @RequestMapping("/mobile/update")
    public View<User> updateMobile(HttpServletRequest request,
                                   HttpServletResponse response,
                                   @Validated @RequestBody UserBean user, BindingResult result) {
        View<User> view = new View<User>(20000, "更新联系方式成功");

        if (result.hasErrors()) {
            view.setCode(40000);
            view.setMessage(ValidateUtil.first(result.getAllErrors()));
        } else {

            TokenPrincipal tokenPrincipal = tokenPrincipalProvider.getTokenPrincipal();

            Map<String, String> params = new HashMap<>();
            params.put("username", user.getMobile());
            params.put("code", user.getCode());
            View<String> resultView = deanAuthClient.checkVerificationCodeEndpoint(params);
            if (resultView.getCode() == View.STATE_OK) {

                String username = tokenPrincipal.getUsername();
                User userDb = userService.selectUserByName(username);
                userDb.setMobile(user.getMobile());
                this.userService.updateUser(userDb);

                /**
                 * 保存手机到到权限系统
                 */
                UserItem userItem = new UserItem();
                userItem.setId(tokenPrincipal.getUserId());
                userItem.setMobile(user.getMobile());
                deanAuthClient.saveUserEndpoint(userItem);

            } else {
                return View.ofError(resultView.getMessage());
            }
        }

        return view;
    }

    /**
     * 修改密码
     *
     * @param request
     * @param response
     * @param user     用户信息 {@link User}
     * @return
     */
    @ApiVersion(1)
    @RequestMapping("/password/update")
    public View<User> updatePassword(HttpServletRequest request,
                                     HttpServletResponse response,
                                     @Validated @RequestBody(required = false) UserBean user, BindingResult result) {

        if (result.hasErrors()) {

            return View.ofError(40000, ValidateUtil.first(result.getAllErrors()));

        } else {

            String username = tokenPrincipalProvider.getTokenPrincipal().getUsername();
            User userDb = userService.selectUserByName(username);
            if (userDb == null) {
                return View.ofError("用户不存在");
            }

            Map<String, String> params = new HashMap<>();
            params.put("username", userDb.getMobile());
            params.put("password", user.getPassword());
            params.put("code", user.getCode());

            View<String> check = deanAuthClient.checkVerificationCodeEndpoint(params);
            if (check.getCode() == View.STATE_OK) {

                params.put("username", username);
                View<Map<String, Object>> resultView = deanAuthClient.registerUserEndpoint(params);
                if (resultView.getCode() == View.STATE_OK) {

                    return View.ofOk("修改密码成功");
                } else {
                    return View.ofError(resultView.getMessage());
                }
            } else {
                return View.ofError(check.getMessage());
            }

        }

    }


    /**
     * 忘记密码,发送验证码
     *
     * @return
     */
    @ApiVersion(1)
    @RequestMapping("/forget/sms/send")
    public View<User> forgetPasswordSmsSend(@Validated @RequestBody(required = false) SendBean user, BindingResult result) {

        if (result.hasErrors()) {
            return View.ofError(40000, ValidateUtil.first(result.getAllErrors()));
        } else {

            String mobile = user.getMobile();
            User userDb = userService.selectUserByMobile(mobile);
            if (userDb == null || StringUtils.isEmpty(userDb.getMobile())) {
                return View.ofError("当前用户没有绑定手机号，请绑定");
            }

            Map<String, String> params = new HashMap<>();
            params.put("username", mobile);
            params.put("send_type", user.getSendType() == null ? SendType.modify.name() : user.getSendType());
            View<String> clientView = deanAuthClient.registerVerificationCodeEndpoint(params);
            if (clientView.getCode() == View.STATE_OK) {
                return View.ofOk("发送成功");
            } else {
                return View.ofError(clientView.getMessage());
            }
        }
    }

    /**
     * 忘记密码,修改密码
     *
     * @param request
     * @param response
     * @param user     用户信息 {@link User}
     * @return
     */
    @ApiVersion(1)
    @RequestMapping("/forget/password/update")
    public View<User> forgetPasswordUpdatePassword(HttpServletRequest request,
                                                   HttpServletResponse response,
                                                   @Validated @RequestBody(required = false) UserBean user, BindingResult result) {

        if (result.hasErrors()) {

            return View.ofError(40000, ValidateUtil.first(result.getAllErrors()));

        } else {

            User userDb = userService.selectUserByMobile(user.getMobile());
            if (userDb == null) {
                return View.ofError("用户不存在");
            }

            Map<String, String> params = new HashMap<>();
            params.put("username", userDb.getMobile());
            params.put("password", user.getPassword());
            params.put("code", user.getCode());

            View<String> check = deanAuthClient.checkVerificationCodeEndpoint(params);
            if (check.getCode() == View.STATE_OK) {

                params.put("username", userDb.getUserName());
                View<Map<String, Object>> resultView = deanAuthClient.registerUserEndpoint(params);
                if (resultView.getCode() == View.STATE_OK) {

                    return View.ofOk("修改密码成功");
                } else {
                    return View.ofError(resultView.getMessage());
                }
            } else {
                return View.ofError(check.getMessage());
            }

        }

    }


    /**
     * 添加子用户
     *
     * @param request
     * @param response
     * @param user     用户信息 {@link User}
     * @return
     */
    @ApiVersion(1)
    @RequestMapping("/child/add")
    public View<User> add(HttpServletRequest request, HttpServletResponse response,
                          @Validated @RequestBody UserBean userBean, BindingResult result) {


        if (result.hasErrors()) {

            return View.ofError(40000, ValidateUtil.first(result.getAllErrors()));

        } else {

            Map<String, String> registerUserParams = new HashMap<>();
            registerUserParams.put("username", userBean.getMobile());
            registerUserParams.put("password", userBean.getPassword() == null ? "123456" : userBean.getPassword());
            registerUserParams.put("code", userBean.getCode());
            String username = tokenPrincipalProvider.getTokenPrincipal().getUsername();
            User parentUser = userService.selectUserByName(username);
            registerUserParams.put("phone", parentUser.getMobile());
            View<Map<String, Object>> registerView = deanAuthClient.registerUserEndpoint(registerUserParams);

            if (registerView.getCode() == View.STATE_OK) {

                parentUser.setChildAccount(0);
                userService.updateUser(parentUser);


                User childUser = userService.selectUserByName(userBean.getMobile());
                if (childUser == null) {
                    childUser = new User();
                    BeanUtils.copy(parentUser, childUser);
                    childUser.setParentId(parentUser.getId());
                    childUser.setUserName(userBean.getMobile());
                    childUser.setNickName(userBean.getNickName());
                    childUser.setMobile(userBean.getMobile());
                    childUser.setChildAccount(1);
                    childUser.setId(null);
                    childUser.setAvatar(null);
                    userService.addUser(childUser);
                } else {
                    childUser.setParentId(parentUser.getId());
                    childUser.setUserName(userBean.getMobile());
                    childUser.setNickName(userBean.getNickName());
                    childUser.setMobile(userBean.getMobile());
                    childUser.setChildAccount(1);
                    userService.updateUser(childUser);
                }

                return View.ofOk("子账号添加成功");

            } else {
                return View.ofError("子账号添加失败:" + registerView.getMessage());
            }

        }
    }

    @HasUser
    @ApiVersion(1)
    @RequestMapping("/child/info/{id}")
    public View<Map<String, Object>> childInfo(@PathVariable Integer id) {

        View<Map<String, Object>> view = new View<>(20000, "获取数据成功");

        User user = userService.selectUser(id);
        if (user == null) {
            user = new User();
        }

        String username = tokenPrincipalProvider.getTokenPrincipal().getUsername();
        User parentUser = userService.selectUserByName(username);

        if (user.getParentId() == null) {
            return View.ofError("获取的用户不是子用户");
        }
        if (!user.getParentId().equals(parentUser.getId())) {
            return View.ofError("获取的用户不是当前账户的子账户");
        }

        List<String> includeFields = new ArrayList<>();
        includeFields.add("id");
        includeFields.add("userName");
        includeFields.add("nickName");
        includeFields.add("mobile");
        includeFields.add("avatar");
        includeFields.add("childAccount");
        includeFields.add("delFlag");
        List<String> sensitiveKey = new ArrayList<>();
        Map<String, Object> userMap = ObjectUtils.objectToMap(user, includeFields, sensitiveKey);
        view.setData(userMap);
        return view;

    }


    /**
     * 获取子用户分页查询列表
     *
     * @param request
     * @param response
     * @return
     */
    @ApiVersion(1)
    @RequestMapping("/child/list")
    public View<List<UserBean>> list(HttpServletRequest request, HttpServletResponse response) {

        String username = tokenPrincipalProvider.getTokenPrincipal().getUsername();
        User parentUser = userService.selectUserByName(username);
        User user = new User();
        user.setParentId(parentUser.getId());
        List<UserBean> userList = userService.findUserList(user);

        return View.ofOk(userList);
    }

    /**
     * 删除子用户
     *
     * @param request
     * @param response
     * @param id
     * @return
     */
    @ApiVersion(1)
    @SuppressWarnings("rawtypes")
    @RequestMapping("/child/state/{id}")
    public View<String> state(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Integer id) {

        String message = "禁用";
        String username = tokenPrincipalProvider.getTokenPrincipal().getUsername();
        User parentUser = userService.selectUserByName(username);
        User user = userService.selectUser(id);

        if ("1".equals(user.getDelFlag())) {
            message = "启用";
        }
        if (user.getChildAccount() == 1) {

            if (user.getParentId() == null) {
                return View.ofError("被" + message + "的用户不是子账户，不能" + message);
            }
            if (!user.getParentId().equals(parentUser.getId())) {
                return View.ofError("被" + message + "的用户不是当前账户的子账户");
            }

            if ("1".equals(user.getDelFlag())) {
                user.setDelFlag(String.valueOf(0));
            } else {
                user.setDelFlag(String.valueOf(1));
            }

            this.userService.updateUser(user);
        } else {
            return View.ofError("被" + message + "的用户不是子账户，不能" + message);
        }

        return View.ofOk(message + "子账户成功");
    }


    /**
     * 经销商注册发送短信
     *
     * @return
     */
    @ApiVersion(1)
    @RequestMapping("/register/status")
    public View<String> platformRegisterStatus() {

        String status = registerStatusCache.getStatus();
        if (StringUtils.isBlank(status)) {
            status = "0";
        }
        return View.ofOk("OK", status);

    }

    /**
     * 经销商注册发送短信
     *
     * @return
     */
    @ApiVersion(1)
    @RequestMapping("/register/status/{val}")
    public View<String> platformRegisterStatus(@PathVariable String val) {

        registerStatusCache.setStatus(val);
        return View.ofOk("OK", val);
    }

    /**
     * 经销商注册发送短信
     *
     * @return
     */
    @ApiVersion(1)
    @RequestMapping("/register/sms/send")
    public View<User> platformSmsSend(@Validated @RequestBody(required = false) SendBean user, BindingResult result) {

        if (result.hasErrors()) {
            return View.ofError(40000, ValidateUtil.first(result.getAllErrors()));
        } else {

            String mobile = user.getMobile();
            Map<String, String> params = new HashMap<>();
            params.put("username", mobile);
            params.put("send_type", user.getSendType() == null ? SendType.modify.name() : user.getSendType());
            View<String> clientView = deanAuthClient.registerVerificationCodeEndpoint(params);
            if (clientView.getCode() == View.STATE_OK) {
                return View.ofOk("发送成功");
            } else {
                return View.ofError(clientView.getMessage());
            }

        }
    }

    /**
     * 经销商注册
     *
     * @param request
     * @param response
     * @param user     用户信息 {@link User}
     * @return
     */
    @ApiVersion(1)
    @RequestMapping("/register")
    public View<User> platformRegisterUser(HttpServletRequest request,
                                           HttpServletResponse response,
                                           @Validated @RequestBody(required = false) UserBean user, BindingResult result) {

        if (result.hasErrors()) {

            return View.ofError(40000, ValidateUtil.first(result.getAllErrors()));

        } else {

            String mobile = user.getMobile();
            if (StringUtils.isBlank(mobile)) {
                return View.ofError("传递的手机号参数不能为空");
            }

            Map<String, String> params = new HashMap<>();
            params.put("username", mobile);
            params.put("password", user.getPassword());
            params.put("code", user.getCode());

            View<String> check = deanAuthClient.checkVerificationCodeEndpoint(params);
            if (check.getCode() == View.STATE_OK) {

                View<Map<String, Object>> resultView = deanAuthClient.registerUserEndpoint(params);
                if (resultView.getCode() == View.STATE_OK) {

                    User childUser = userService.selectUserByName(mobile);
                    if (childUser == null) {
                        childUser = new User();
                        childUser.setUserName(mobile);
                        childUser.setNickName(mobile);
                        childUser.setMobile(mobile);
                        childUser.setAddress("");
                        childUser.setUserLeaf(Boolean.TRUE);
                        childUser.setUserNo("Z000009");
                        childUser.setUserIndex("CSYH");
                        childUser.setRegionId(23);
                        childUser.setRegionCode("230");
                        childUser.setChildAccount(0);
                        childUser.setId(null);
                        childUser.setAvatar(null);
                        childUser.setOrderTakeUser("简冬梅");
                        userService.addUser(childUser);
                    } else {
                        childUser.setUserName(mobile);
                        childUser.setNickName(mobile);
                        childUser.setMobile(mobile);
                        childUser.setChildAccount(0);
                        childUser.setId(null);
                        childUser.setAvatar(null);
                        childUser.setOrderTakeUser("简冬梅");
                        userService.updateUser(childUser);
                    }
                    return View.ofOk("修改密码成功");
                } else {
                    return View.ofError(resultView.getMessage());
                }
            } else {
                return View.ofError(check.getMessage());
            }

        }

    }

}
